package com.tanhua.mongo.utils;

import com.tanhua.model.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * 自增pid获取工具类
 */
@Component
public class IdWorker {

    @Autowired
    private MongoTemplate mongoTemplate;

    //返回自增pid的方法
    public Long getNextId(String collName) {
        //构建条件
        Query query = new Query(Criteria.where("collName").is(collName));

        //设置某个字段自增加1
        Update update = new Update();
        update.inc("seqId", 1);

        //设置查询前更新为自增后的值
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);

        //查询并返回结果
        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }
}